package com.eqdd.yiqidian.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.view.SurfaceView;

import com.bulong.rudeness.RudenessScreenHelper;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.bean.rebuild.GroupListResultBean;
import com.eqdd.yiqidian.listener.rongyun.ConnectionStatusListener;
import com.eqdd.yiqidian.listener.rongyun.ReceiveMessageListener;
import com.eqdd.yiqidian.rongyun.MingpianMessage;
import com.eqdd.yiqidian.rongyun.MingpianMessageItemProvider;
import com.eqdd.yiqidian.rongyun.MyExtensionModel;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.utils.EncryptUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.zxy.tiny.Tiny;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;

import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import cafe.adriel.androidaudioconverter.callback.ILoadCallback;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jpush.android.api.JPushInterface;
import cn.smssdk.SMSSDK;
import io.rong.callkit.RongCallAction;
import io.rong.callkit.RongCallKit;
import io.rong.callkit.RongCallProxy;
import io.rong.calllib.IRongCallListener;
import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.calllib.RongCallSession;
import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIMClientWrapper;
import io.rong.imkit.model.GroupUserInfo;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.OkHttpClient;
import shortbread.Shortbread;

//import com.uuzuche.lib_zxing.activity.ZXingLibrary;

/**
 * Created by vzhihao on 2016/11/1.
 */
public class BaseApplication extends Application {
    //运用list来保存们每一个activity是关键
    private List<Activity> mList = new LinkedList();
    //为了实现每次使用该类时不创建新的对象而创建的静态对象
    private static BaseApplication application;
    //应用程序启动就调用，代表整个应用
    public static Handler handler;

    public static Context context;

    public static int mainTid;
    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY = "1b8496b059b30";
    private static String APPSECRET = "daa0b3099e8bfd736af50955e79da286";
    private static String BUGLY_APPID = "56663f923a";

    @Override
    public void onCreate() {
        super.onCreate();
        String certificateSHA1Fingerprint = EncryptUtil.getCertificateSHA1Fingerprint(this);
        System.out.println(certificateSHA1Fingerprint);
        context = application = this;
        handler = new Handler();
        mainTid = android.os.Process.myTid();
        Shortbread.create(this);
        AndroidAudioConverter.load(this, new ILoadCallback() {
            @Override
            public void onSuccess() {
                // Great!
                System.out.println("great");
            }

            @Override
            public void onFailure(Exception error) {
                System.out.println(error);
                System.out.println("FFmpeg is not supported by device");
            }
        });
        WindowUtil.init(this);
        new RudenessScreenHelper(this, 630).activate();
        Tiny.getInstance().init(this);
//        ZXingLibrary.initDisplayOpinion(this);
        SMSSDK.initSDK(this, APPKEY, APPSECRET, false);


        /*#######################极光推送######################*/

        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        JPushInterface.stopCrashHandler(this);
        JShareInterface.setDebugMode(true);
        JShareInterface.init(this);

        /*#######################极光推送######################*/


        Stetho.initializeWithDefaults(this);
        ShortcutBadger.applyCount(context, 7);


        /*#######################BUGLY######################*/

        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
         * 不设置会默认所有activity都可以显示弹窗;
         */
        Beta.canShowUpgradeActs.add(MainActivity.class);
        Bugly.init(getApplicationContext(), BUGLY_APPID, false);
        /*#######################BUGLY######################*/

        initRongIm();
        RongIM.setConnectionStatusListener(new ConnectionStatusListener());
        RongIM.setOnReceiveMessageListener(new ReceiveMessageListener());
//        RongCallProxy.getInstance().setCallListener();
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
        RongIM.setGroupInfoProvider(s -> {
            System.out.println("融云服务器来获取group数据了" + s);
            GroupListResultBean groupById = GreenDaoUtil.getGroupById(s);
            if (groupById == null) {
                return null;
            } else {
                return new Group(groupById.getGroupid(), groupById.getGroupname(), Uri.parse(groupById.getGroupphoto()));
            }
        }, true);
//        RongIM.setGroupUserInfoProvider(new RongIM.GroupUserInfoProvider() {
//            @Override
//            public GroupUserInfo getGroupUserInfo(String s, String s1) {
//                return null;
//            }
//        },true);
        List<IExtensionModule> extensionModules = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultExtensionModule = null;
        if (extensionModules != null) {
            for (IExtensionModule extensionModule : extensionModules) {
                if (extensionModule instanceof DefaultExtensionModule) {
                    defaultExtensionModule = extensionModule;
                    break;
                }
            }
            if (defaultExtensionModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultExtensionModule);
            }
            RongExtensionManager.getInstance().registerExtensionModule(new MyExtensionModel());
        }
        RongIM.registerMessageType(MingpianMessage.class);
        RongIM.registerMessageTemplate(new MingpianMessageItemProvider());

        initOkgoHttp(this);
        registerActivityLifecycleCallbacks(new BaseActivityLifeCallBack());
    }

    private void initOkgoHttp(Context context) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addNetworkInterceptor(new StethoInterceptor());
        builder.addInterceptor(loggingInterceptor);
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(context)));
//---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
//        HttpHeaders headers = new HttpHeaders();
//        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
//        headers.put("commonHeaderKey2", "commonHeaderValue2");
//        HttpParams params = new HttpParams();
//        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
//        params.put("commonParamsKey2", "这里支持中文参数");
//-------------------------------------------------------------------------------------//

        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);
        //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);
    }

    private void initRongIm() {
        /**
         *
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(this);
            RongIMClient.init(this);

            if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

                DemoContext.init(this);
            }
        }
    }

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return
     */
    @SuppressLint("NewApi")
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Handler getHandler() {
        return handler;
    }

    public static Context getContext() {
        return context;
    }

    public synchronized static BaseApplication getApplication() {
        return application;
    }

    public List<Activity> getActivities() {
        return mList;
    }

    //杀进程
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    public static int getMainTid() {
        return mainTid;
    }
}
